using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data;
using System.Configuration;
using System.Text;
using System.IO;
using System.Collections;
using Microsoft.Win32;
using Microsoft.VisualBasic;

public partial class testcase_regression : System.Web.UI.Page
{
    int countResult = 0;
    string gsAllTransactions = "";
    int liLnkPos = 0;
    string lsLinkClientId = "";
    string liRowId = "";
    string lsColumnData = "";
    string lsTransactonName = "";
    bool isReady4InsertData = false;

    SQLInteract objSQL = new SQLInteract();


    protected void Page_Load(object sender, EventArgs e)
    {
        //Delete cache to handle browser back button event on logout
        Response.Buffer = true;
        Response.ExpiresAbsolute = DateTime.Now.AddDays(-1d);
        Response.Expires = -1500;
        HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.CacheControl = "no-cache";
        if (Session["UserName"] == null) //Redirect to login if session expires
        {
            Response.Redirect("Login.aspx", true);
        }        
        lblFlowType.Text = Session["PageFlow"].ToString().Trim();
        Master.Page.Title = "GSTAR-" + Session["PageFlow"].ToString().Trim();
    }

    protected void Page_Init(object sender, EventArgs e)
    {
        btnSave.Visible = false;
        btnRunBatch.Visible = false;
        if (!Page.IsPostBack)
        {
            hdnTest.Value = "";

            //Delete old data if any...
            try
            {
                objSQL.sqlExecuteNonQuery("Delete from Transaction_Tb where UsrId='" + Session["UserId"].ToString() + "' and FlowType='" + Session["FlowType"].ToString().Trim() + "' Delete from TEST_CASE_SELECTION_SHEET_GEN_TB where UserId='" + Session["UserId"].ToString() + "' and FlowType='" + Session["FlowType"].ToString().Trim() + "'");
            }
            catch (Exception ex)
            {
                this.ClientScript.RegisterStartupScript(this.Page.GetType(), "Alert", "<script language=\"javascript\" type=\"text/javascript\" > alert(\"Error: " + ex.Message + "\");</script>", false);
            }
            finally
            {
                txtBtchName.Attributes.Add("onkeypress", "return clickButton(event,'" + btnchngName.ClientID + "')");
            }
        }
        CreateDynamicRows();
        LoadExistingBatches('n');
        pnlExistingBatch.Visible = false;
        lblExistingBatch.Visible = false;
    }
    
    protected void Page_PreInit(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            try
            {
                Session["FlowType"] = Request.QueryString["ref"].Trim().ToString();//set session value from querystring
                string flow = objSQL.sqlExecuteScalar("Select Text from Menu where MenuID='" + Session["FlowType"].ToString().Trim() + "'").ToString().Trim();
                Session["PageFlow"] = flow;
            }
            catch (Exception ex)
            {
                this.ClientScript.RegisterStartupScript(this.Page.GetType(), "Alert", "<script language=\"javascript\" type=\"text/javascript\" > alert(\"Error:" + ex.Message + "\");</script>", false);
            }
        }
    }


    void DisplayCheckBoxes(string btnText) // Display transaction checkboxes
    {
        hdnTest.Value = "";
        hdnChangeStatus.Value = "0";
        lblTcTransactionDetails.Text = "";
        pnlScenarios.Visible = false;
        int MaxTrans = int.Parse(ConfigurationManager.AppSettings["MaxTrans"]);
        if ((int)ViewState["liTransactionCnt"] < MaxTrans)
        {
            Table DynTable = new Table();
            DynTable.ID = "TbCategories";
            DynTable.BorderWidth = 0;
            DynTable.CellPadding = 0;
            DynTable.CellPadding = 0;

            if (btnText.Trim().ToString().IndexOf("&nbsp;") != -1)
            {
                btnText = "["+ btnText.Replace("&nbsp;", " ").Trim().ToString()+ "]";
            }
            DataSet CheckItemsDta = new DataSet();
            try
            {
                CheckItemsDta = objSQL.ReturnDataAdapter("Select distinct Group_Name,Group_Order from CollectionScenarios_TB_Generic where [" + btnText.Trim() + "] = 1 and FlowType='" + Session["FlowType"].ToString().Trim() + "' order by Group_Order");
                if (CheckItemsDta.Tables.Count > 0)
                {
                    if (CheckItemsDta.Tables[0].Rows.Count > 0)
                    {
                        pnlScenarios.Visible = true;
                    }
                    pnlScenarios.Controls.Add(new LiteralControl("<br/>"));
                    foreach (DataRow row in CheckItemsDta.Tables[0].Rows)
                    {
                        TableCell tbcell1 = new TableCell();
                        TableCell tbcell2 = new TableCell();
                        TableCell tbcell3 = new TableCell();
                        TableRow tbrow = new TableRow();
                        tbcell1.BackColor = System.Drawing.Color.Gainsboro;
                        tbcell2.BackColor = System.Drawing.Color.Gainsboro;
                        tbrow.Cells.Add(tbcell1);
                        tbrow.Cells.Add(tbcell2);
                        tbrow.Cells.Add(tbcell3);
                        DynTable.Rows.Add(tbrow);

                        CheckBox chkbxDel = new CheckBox();
                        chkbxDel.ID = row["Group_Name"].ToString().Trim();
                        tbcell1.Controls.Add(new LiteralControl("&nbsp;"));
                        tbcell1.Controls.Add(chkbxDel);
                        tbcell1.Controls.Add(new LiteralControl("&nbsp;"));
                        chkbxDel.Attributes.Add("onclick", "setCheckedItems('" + row["Group_Name"].ToString() + "','" + row["Group_Order"].ToString().Trim() + "','"+ hdnTest.ClientID+"');");
                        tbcell2.Text = "&nbsp;&nbsp;" + row["Group_Name"].ToString() + "&nbsp;&nbsp;";
                        tbcell3.Text = " <img id='" + row["Group_Order"].ToString().Trim() + "'style='visibility:hidden' src='Images/details.gif' onclick=showpopup('" + row["Group_Order"].ToString().Trim() + "');>";
                        pnlScenarios.Controls.Add(DynTable);
                    }
                }
            }
            catch (Exception ex)
            {
                CheckItemsDta.Dispose();
                this.ClientScript.RegisterStartupScript(this.Page.GetType(), "Alert", "<script language=\"javascript\" type=\"text/javascript\" >alert(\"Error: " + ex.Message + "\");</script>", false);
            }
            finally
            {
                CheckItemsDta.Dispose();
                lblExistingBatch.Visible = false;
            }
        }
        else
        {
            lblEdittingFor.Text = "";
        }
    }

    void LoadExistingBatches(char render)  //Load already saved batches
    {
        int rowId = 0;
        Table DynTable1 = new Table();
        DynTable1.ID = "TbExistingBatches";
        DynTable1.BorderWidth = 0;
        DynTable1.CellPadding = 0;
        DynTable1.CellPadding = 0;
        DataSet CheckItemsDta = new DataSet();
        pnlExistingBatch.Controls.Clear();
        try
        {
            CheckItemsDta = objSQL.ReturnDataAdapter("Select distinct DateTimeSaved, count(DateTimeSaved) as Cnt,RunStatus,RunTime,AliasBatchName from Transaction_ARCH_TB where usrid='" + Session["UserId"].ToString() + "' and FlowType='" + Session["FlowType"].ToString().Trim() + "' group by DateTimeSaved,RunStatus,RunTime,AliasBatchName order by runtime");
            if (CheckItemsDta.Tables.Count > 0)
            {
                if (CheckItemsDta.Tables[0].Rows.Count > 0)
                {
                    lblExistingBatch.Visible = true;
                    lbDeleteSlctd.Visible = true;
                    pnlExistingBatch.Visible = true;
                    TableRow DynRow0;
                    DynRow0 = new TableRow();
                    TableCell DynCell0 = new TableCell();
                    TableCell DynCell1 = new TableCell();
                    TableCell DynCell2 = new TableCell();
                    TableCell DynCell3 = new TableCell();
                    TableCell DynCell4 = new TableCell();
                    TableCell DynCell5 = new TableCell();
                    TableCell DynCell6 = new TableCell();
                    DynCell0.Width = 30;
                    DynCell0.HorizontalAlign = HorizontalAlign.Center;
                    DynCell1.Width = 220;
                    DynCell1.HorizontalAlign = HorizontalAlign.Center;
                    DynCell2.Width = 95;
                    DynCell2.HorizontalAlign = HorizontalAlign.Center;
                    DynCell3.Width = 60;
                    DynCell3.HorizontalAlign = HorizontalAlign.Center;
                    DynCell4.Width = 110;
                    DynCell4.HorizontalAlign = HorizontalAlign.Center;
                    DynCell5.Width = 110;
                    DynCell5.HorizontalAlign = HorizontalAlign.Center;
                    DynCell6.Width = 110;
                    DynCell6.HorizontalAlign = HorizontalAlign.Center;

                    DynRow0.Cells.Add(DynCell0);
                    DynRow0.Cells.Add(DynCell1);
                    DynRow0.Cells.Add(DynCell2);
                    DynRow0.Cells.Add(DynCell3);
                    DynRow0.Cells.Add(DynCell4);
                    DynRow0.Cells.Add(DynCell5);
                    DynRow0.Cells.Add(DynCell6);
                    DynTable1.Rows.Add(DynRow0);
                    DynRow0.CssClass = "thbg";

                    CheckBox chkbxDel1 = new CheckBox();
                    chkbxDel1.ID = "chkbxDel1";
                    chkbxDel1.ToolTip = "Select All";
                    DynCell0.Controls.Add(new LiteralControl("&nbsp;"));
                    DynCell0.Controls.Add(chkbxDel1);
                    DynCell0.Controls.Add(new LiteralControl("&nbsp;"));
                    chkbxDel1.Attributes.Add("onClick", "selectAll('" + hdnDelID.ClientID + "');");

                    Label lblBatchName = new Label();
                    lblBatchName.Text = "<font color=white size=2 face=verdana>Batch Name</font>";
                    DynCell1.Controls.Add(new LiteralControl("&nbsp;"));
                    DynCell1.Controls.Add(lblBatchName);
                    DynCell1.Controls.Add(new LiteralControl("&nbsp;"));

                    Label lblBatchLD = new Label();
                    lblBatchLD.Text = "<font color=white size=2 face=verdana>Load</font>";
                    DynCell2.Controls.Add(new LiteralControl("&nbsp;"));
                    DynCell2.Controls.Add(lblBatchLD);
                    DynCell2.Controls.Add(new LiteralControl("&nbsp;"));

                    Label lblBatchDel = new Label();
                    lblBatchDel.Text = "<font color=white size=2 face=verdana>Delete</font>";
                    DynCell3.Controls.Add(new LiteralControl("&nbsp;"));
                    DynCell3.Controls.Add(lblBatchDel);
                    DynCell3.Controls.Add(new LiteralControl("&nbsp;"));

                    Label lblBatchRprt = new Label();
                    lblBatchRprt.Text = "<font color=white size=2 face=verdana>Report</font>";
                    DynCell4.Controls.Add(new LiteralControl("&nbsp;"));
                    DynCell4.Controls.Add(lblBatchRprt);
                    DynCell4.Controls.Add(new LiteralControl("&nbsp;"));

                    Label lblDShead = new Label();
                    lblDShead.Text = "<font color=white size=2 face=verdana>DataTable</font>";
                    DynCell5.Controls.Add(new LiteralControl("&nbsp;"));
                    DynCell5.Controls.Add(lblDShead);
                    DynCell5.Controls.Add(new LiteralControl("&nbsp;"));

                    Label lblTShead = new Label();
                    lblTShead.Text = "<font color=white size=2 face=verdana>TimeStamp</font>";
                    DynCell6.Controls.Add(new LiteralControl("&nbsp;"));
                    DynCell6.Controls.Add(lblTShead);
                    DynCell6.Controls.Add(new LiteralControl("&nbsp;"));
                    foreach (DataRow row in CheckItemsDta.Tables[0].Rows)
                    {
                        rowId = rowId + 1;
                        TableRow DynRow1 = new TableRow();

                        TableCell DynCell10 = new TableCell();
                        TableCell DynCell11 = new TableCell();
                        TableCell DynCell12 = new TableCell();
                        TableCell DynCell13 = new TableCell();
                        TableCell DynCell14 = new TableCell();
                        TableCell DynCell15 = new TableCell();
                        TableCell DynCell16 = new TableCell();
                        DynCell10.Width = 30;
                        DynCell11.Width = 220;
                        DynCell12.Width = 95;
                        DynCell13.Width = 60;
                        DynCell14.Width = 110;
                        DynCell15.Width = 250;
                        DynRow1.Cells.Add(DynCell10);
                        DynRow1.Cells.Add(DynCell11);
                        DynRow1.Cells.Add(DynCell12);
                        DynRow1.Cells.Add(DynCell13);
                        DynRow1.Cells.Add(DynCell14);
                        DynRow1.Cells.Add(DynCell16);
                        DynRow1.Cells.Add(DynCell15);
                        DynTable1.Rows.Add(DynRow1);
                        if (rowId % 2 == 0)
                        {
                            DynRow1.BackColor = System.Drawing.Color.Gainsboro;
                        }
                        else
                        {
                            DynRow1.BackColor = System.Drawing.Color.WhiteSmoke;
                        }
                        CheckBox chkbxDel = new CheckBox();
                        chkbxDel.ID = row[0].ToString().Trim();
                        DynCell10.Controls.Add(new LiteralControl("&nbsp;"));
                        DynCell10.Controls.Add(chkbxDel);
                        DynCell10.Controls.Add(new LiteralControl("&nbsp;"));
                        chkbxDel.Attributes.Add("onClick", "setCheckedItemsForDel('" + chkbxDel.ID + "','" + hdnDelID.ClientID + "');");

                        Label lblBatch = new Label();
                        lblBatch.ID = "lblBatch" + rowId.ToString();
                        lblBatch.Text = "<font color='#26282C'>" + row[4].ToString().Trim() + "</font> <font color=gray>[TC Count : " + row[1].ToString().Trim() + "]</font>";
                        DynCell11.Controls.Add(new LiteralControl("&nbsp;"));
                        DynCell11.Controls.Add(lblBatch);
                        DynCell11.Controls.Add(new LiteralControl("&nbsp;"));

                        //Load Batch
                        DynCell12.Controls.Add(new LiteralControl("&nbsp;"));
                        LinkButton lnkLoadBatch = new LinkButton();
                        lnkLoadBatch.ID = "lnkLoadBatch" + rowId.ToString();
                        lnkLoadBatch.ToolTip = "Click to Load batch.";
                        lnkLoadBatch.CssClass = "RemoveUnderline";
                        lnkLoadBatch.CommandName = row[0].ToString().Trim();
                        if(rowId%2==0)
                        {
                            lnkLoadBatch.Text = "Load Batch<font color=gainsboro>" + row[2].ToString().Trim().ToString() + "</font>";
                        }
                        else
                        {
                            lnkLoadBatch.Text = "Load Batch<font color=whitesmoke>" + row[2].ToString().Trim().ToString() + "</font>";
                        }                        
                        lnkLoadBatch.Click += new EventHandler(lnkLoadBatch_Click);
                        lnkLoadBatch.OnClientClick = "if (!confirm('Are you sure to load this batch (" + row[4].ToString().Trim() + ")? Current unsaved data(if any) will be lost.')) return false";
                        DynCell12.Controls.Add(new LiteralControl("&nbsp;"));
                        DynCell12.Controls.Add(lnkLoadBatch);
                        DynCell12.Controls.Add(new LiteralControl("&nbsp;"));

                        //Delete existing batch
                        DynCell13.Controls.Add(new LiteralControl("&nbsp;"));
                        LinkButton lnkDeleteBatch = new LinkButton();
                        lnkDeleteBatch.ToolTip = "Click to delete batch.";
                        lnkDeleteBatch.CssClass = "RemoveUnderline";
                        lnkDeleteBatch.ID = "lnkDeleteBatch" + rowId.ToString();
                        lnkDeleteBatch.CommandName = row[0].ToString().Trim();
                        lnkDeleteBatch.Text = "Delete";
                        lnkDeleteBatch.Click += new EventHandler(lnkDeleteBatch_Click);
                        lnkDeleteBatch.OnClientClick = "if (!confirm('Are you sure to delete this batch (" + row[4].ToString().Trim() + ")? Current batch data will be lost.')) return false";
                        DynCell13.Controls.Add(new LiteralControl("&nbsp;"));
                        DynCell13.Controls.Add(lnkDeleteBatch);
                        DynCell13.Controls.Add(new LiteralControl("&nbsp;"));
                        DynCell13.Controls.Add(new LiteralControl("<br/>"));
                        DynCell13.HorizontalAlign = HorizontalAlign.Center;

                        //Report
                        DynCell14.Controls.Add(new LiteralControl("&nbsp;"));
                        LinkButton lnkBatchResult = new LinkButton();
                        lnkBatchResult.ToolTip = "Click to view batch run results.";
                        lnkBatchResult.ID = "lnkBatchResult" + rowId.ToString();
                        lnkBatchResult.CssClass = "RemoveUnderline";
                        lnkBatchResult.Text = row[2].ToString().Trim().ToString() == "Y" ? "<a href=\"#\" onclick=\"javascript: DisplayResults('" + row[0].ToString().Trim() + "|" + row[4].ToString().Trim() + "','" + Session["FlowType"].ToString().Trim() + "');\" class='RemoveUnderline'>View Results</a>" : "--";
                        DynCell14.Controls.Add(new LiteralControl("&nbsp;"));
                        DynCell14.Controls.Add(lnkBatchResult);
                        DynCell14.Controls.Add(new LiteralControl("&nbsp;"));
                        DynCell14.HorizontalAlign = HorizontalAlign.Center;

                        //View Datasheet
                        DynCell16.Controls.Add(new LiteralControl("&nbsp;"));
                        Label lnkDatasheet = new Label();
                        lnkDatasheet.ToolTip = "Click to view batch Datasheet.";
                        lnkDatasheet.ID = "lnkDatasheet" + rowId.ToString();
                        lnkDatasheet.CssClass = "RemoveUnderline";
                        lnkDatasheet.Text = row[2].ToString().Trim().ToString() == "Y" ? "<a href='\\\\\\\\20.198.145.93\\\\avivat\\\\FrameworkReconstruction\\\\DataSheet\\\\" + Session["UserId"].ToString()+ "\\\\" + row[0].ToString().Trim() + ".xls' class='RemoveUnderline'>View Datasheet</a>":"--";
                        DynCell16.Controls.Add(new LiteralControl("&nbsp;"));
                        DynCell16.Controls.Add(lnkDatasheet);
                        DynCell16.Controls.Add(new LiteralControl("&nbsp;"));
                        DynCell16.HorizontalAlign = HorizontalAlign.Center;

                        //Batch Run Time
                        DynCell15.Controls.Add(new LiteralControl("&nbsp;"));
                        Label lblBatchRunTime = new Label();
                        lblBatchRunTime.ID = "lblBatchRunTime" + rowId.ToString();
                        lblBatchRunTime.Text = row[3].ToString().Trim().ToString() != "1/1/1900 12:00:00 AM" ? "<font color='#26282C'>" + row[3].ToString() + "</font>" : "";
                        DynCell15.Controls.Add(new LiteralControl("&nbsp;"));
                        DynCell15.Controls.Add(lblBatchRunTime);
                        DynCell15.Controls.Add(new LiteralControl("&nbsp;"));
                        DynCell15.HorizontalAlign = HorizontalAlign.Center;

                        pnlExistingBatch.Controls.Add(DynTable1);
                    }
                }
                else
                {
                    lblExistingBatch.Visible = false;
                    lbDeleteSlctd.Visible = false;
                    pnlExistingBatch.Visible = false;
                }
            }
        }
        catch (Exception ex)
        {
            lblExistingBatch.Visible = false;
            lbDeleteSlctd.Visible = false;
            pnlExistingBatch.Visible = false;
            this.ClientScript.RegisterStartupScript(this.Page.GetType(), "Alert", "<script language=\"javascript\" type=\"text/javascript\" >alert(\"Error: " + ex.Message + "\");</script>", false);
        }
        finally
        {
            CheckItemsDta.Dispose();
            pnlScenarios.Visible = false;
            pnlTcTransactionDetails.Visible = false;
        }
    }

    void CreateDynamicRows() //Create testcase table
    {
        ContentPlaceHolder mainContent = (ContentPlaceHolder)this.Master.FindControl("ContentPlaceHolder1");

        pnlTestCaseRow.Controls.Clear();// Remove(mainContent.FindControl("TbTestCaseTransactions"));
        if (Session["UserId"] == null)
        {
            Response.Redirect("Login.aspx", true);
        }

        StringBuilder sbSearchQry = new StringBuilder("");
        sbSearchQry.Append("Delete from Transaction_Tb where UsrId='" + Session["UserId"].ToString() + "'and FlowType='" + Session["FlowType"].ToString().Trim() + "' Delete from TEST_CASE_SELECTION_SHEET_GEN_TB where UserId='" + Session["UserId"].ToString() + "' and FlowType='" + Session["FlowType"].ToString().Trim() + "'");
        
        try
        {
            if (isReady4InsertData == true)
            {
                DataSet dsFeilds = objSQL.ReturnDataAdapter("select FID,FTEXT from [TC_FEILDS] INNER JOIN [Menu] ON [TC_FEILDS].BUS_TYPE=[Menu].BUS_TYPE WHERE [Menu].[MenuID]='" + Session["FlowType"] + "' ");
                foreach (DataRow row in dsFeilds.Tables[0].Rows)
                {
                    for (int i = 1; i <= Int32.Parse(txtTestCases.Text); i++)
                    {
                        sbSearchQry.Append("Insert into Transaction_Tb([TestCase],[TransactionText],[UsrId],[SrlNmbr],[UpdateInd],[FlowType],[Field]) values('TC" + i.ToString() + "','-','" + Session["UserId"].ToString() + "'," + i.ToString() + ",'N','" + Session["FlowType"].ToString().Trim() + "','"+ row[1].ToString().Trim() +"') Insert into TEST_CASE_SELECTION_SHEET_GEN_TB values('TC" + i.ToString() + "','','','','','','" + Session["FlowType"].ToString().Trim() + "','" + Session["UserId"].ToString() + "',0)");
                    }
                }
                objSQL.sqlExecuteNonQuery(sbSearchQry.ToString());  
             }
                      
        }
        catch (Exception ex)
        {
            this.ClientScript.RegisterStartupScript(this.Page.GetType(), "Alert", "<script language=\"javascript\" type=\"text/javascript\" > alert(\"Error: " + ex.Message + "\");</script>", false);
        }
        finally
        {
            {
                string selQ = "Select count(*) from Transaction_Tb where UsrId='" + Session["UserId"].ToString() + "' and FlowType='" + Session["FlowType"].ToString() + "'";
                int cnt = int.Parse(objSQL.sqlExecuteScalar(selQ));
              
                if (cnt > 0)
                {
                    
                     createdynamicfinally();
                }
            }
        }
    }

    void createdynamicfinally()  //Final step to create testcase table
    {
        int tcCount = 0;
        Table DynTable = new Table();
        DynTable.ID = "TbTestCaseTransactions";
        DynTable.BorderWidth = 0;
        DynTable.CellPadding = 0;
        DynTable.CellPadding = 0;
        DynTable.CssClass = "TCtableborder";
        DynTable.BackColor = System.Drawing.Color.PaleGoldenrod;
        string lsRowUpdateStatusStr = "";
        
        try
        {
            string selQ = "Select distinct [TestCase],SrlNmbr from Transaction_Tb where UsrId='" + Session["UserId"].ToString() + "' and FlowType='" + Session["FlowType"].ToString() + "' order by TestCase";
            DataSet dstable = objSQL.ReturnDataAdapter(selQ);
            tcCount = dstable.Tables[0].Rows.Count;
            if (dstable.Tables[0].Rows.Count>0)
            {
                if (lblBatchName.Text.Trim().ToString().IndexOf("Executed") != -1)
                {
                    btnSave.Enabled = false;
                }
                else
                {
                    btnSave.Enabled = true;
                }
         
                for (int i = 1; i <= tcCount; i++)
                {

                    TableRow DynRow1 = new TableRow();
                    TableCell tbCell;

                    tbCell = new TableCell();
                    Label lbl_TC = new Label();
                    lbl_TC.Text = "<font color='Black'><b>TC" +dstable.Tables[0].Rows[i - 1]["SrlNmbr"].ToString() + "</b></font>";
                    tbCell.Controls.Add(new LiteralControl("&nbsp;&nbsp;"));
                    tbCell.Controls.Add(lbl_TC);
                    tbCell.Controls.Add(new LiteralControl("&nbsp;&nbsp;"));

                    //TC Details
                    LinkButton lnkTC_Details = new LinkButton();
                    lnkTC_Details.CssClass = "RemoveUnderline";
                    lnkTC_Details.ID = "TC" + dstable.Tables[0].Rows[i - 1]["SrlNmbr"].ToString();
                    tbCell.Controls.Add(new LiteralControl("<br>"));
                    lnkTC_Details.Text = "&nbsp;<font color=Red>Details</font>&nbsp;";
                    lnkTC_Details.Click += new EventHandler(lnkTC_Details_Click);
                    tbCell.Controls.Add(lnkTC_Details);
                    DynRow1.Cells.Add(tbCell);

                    string menuQ = "select [BUS_TYPE]  FROM [AvivaTPortal].[dbo].[Menu] where [MenuID]=" + Session["FlowType"] + "";
                    DataSet dsMenu = objSQL.ReturnDataAdapter(menuQ);
                    string fieldtype = dsMenu.Tables[0].Rows[0][0].ToString();
                    DataSet ds = new DataSet();
                    ds = objSQL.ReturnDataAdapter("SELECT FID,FTEXT FROM [AvivaTPortal].[dbo].[TC_FEILDS] where [BUS_TYPE]='" + fieldtype + "' ");
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        foreach (DataRow row in ds.Tables[0].Rows)
                        {
                            DataSet dsTB = objSQL.ReturnDataAdapter("Select distinct Field, UpdateInd,[TESTCASE] from Transaction_Tb where UsrId='" + Session["UserId"].ToString() + "' and FlowType='" + Session["FlowType"].ToString() + "' and Field='" + row[1].ToString() + "' order by TESTCASE");
                            tbCell = new TableCell();
                            //tbCell.ID = "tbCell" + sDRdr["SrlNmbr"].ToString();
                            tbCell.Controls.Add(new LiteralControl("&nbsp;"));
                            tbCell.HorizontalAlign = HorizontalAlign.Center;
                            Image img = new Image();
                            img.ID = "img" + row[0].ToString().Trim() + int.Parse(dstable.Tables[0].Rows[i-1]["SrlNmbr"].ToString());
                            img.ImageUrl = dsTB.Tables[0].Rows[i - 1]["UpdateInd"].ToString() != "N" ? "Images/Green-icon.png" : "Images/Red-icon.png";
                            tbCell.Controls.Add(img);
                            LinkButton lnkbtn = new LinkButton();
                            lnkbtn.CssClass = "RemoveUnderline";
                            lnkbtn.ID = "lnk" + row[1].ToString().Trim() + "_LNK_" + int.Parse(dstable.Tables[0].Rows[i-1]["SrlNmbr"].ToString());
                            lnkbtn.Text = dsTB.Tables[0].Rows[i - 1]["UpdateInd"].ToString() != "N" ? "<font color=green><b>" + row[1].ToString().Trim() + "</b></font>" : "<font color=black>" + row[1].ToString().Trim() + "</font>";
                            lnkbtn.Click += new EventHandler(lnkbtn_Click);
                            tbCell.Controls.Add(new LiteralControl("&nbsp;"));
                            tbCell.BackColor = System.Drawing.Color.White;
                            tbCell.Controls.Add(lnkbtn);
                            tbCell.Controls.Add(new LiteralControl("&nbsp;"));
                            DynRow1.Cells.Add(tbCell);
                        }
                    }
                    else
                    {
                        this.ClientScript.RegisterStartupScript(this.Page.GetType(), "Alert", "<script language=\"javascript\" type=\"text/javascript\" >alert(\"Error: " + "No TestCase feilds found." + "\");</script>", false);
                    }

                    //Delete row
                    TableCell tbcelldel = new TableCell();
                    tbcelldel.VerticalAlign = VerticalAlign.NotSet;
                    ImageButton lnkDelete = new ImageButton();
                    lnkDelete.ID = "lnkDelete_LNK_" + int.Parse(dstable.Tables[0].Rows[i-1]["SrlNmbr"].ToString());
                    lnkDelete.ImageUrl = "Images/Deletecross.png";
                    lnkDelete.Click += new System.Web.UI.ImageClickEventHandler(lnkDelete_Click);
                    lnkDelete.OnClientClick = "if (!confirm('Are you sure to delete " + dstable.Tables[0].Rows[i-1]["SrlNmbr"].ToString().Trim() + "? This data will be lost and can not be recovered.')) return false";
                    tbcelldel.BackColor = System.Drawing.Color.PaleGoldenrod;
                    tbcelldel.Controls.Add(lnkDelete);
                    tbcelldel.Controls.Add(new LiteralControl("&nbsp;"));
                    tbcelldel.Controls.Add(new LiteralControl("<br/>"));
                    DynRow1.Cells.Add(tbcelldel);

                    //Add new row
                    if (i == tcCount)
                    {
                        TableCell tbcelladdtc = new TableCell();
                        tbcelladdtc.VerticalAlign = VerticalAlign.NotSet;
                        ImageButton lnkaddtc = new ImageButton();
                        lnkaddtc.ID = "lnkaddtc_LNK_" + int.Parse(dstable.Tables[0].Rows[i - 1]["SrlNmbr"].ToString());
                        lnkaddtc.ImageUrl = "Images/add.png";
                        lnkaddtc.ToolTip = "Add Testcase to batch";
                        lnkaddtc.Click += new System.Web.UI.ImageClickEventHandler(lnkbtnAddCase_Click);
                        lnkaddtc.OnClientClick = "if (!confirm('Are you sure to add new row to existing batch.')) return false";
                        tbcelladdtc.BackColor = System.Drawing.Color.PaleGoldenrod;
                        tbcelladdtc.Controls.Add(lnkaddtc);
                        tbcelladdtc.Controls.Add(new LiteralControl("&nbsp;"));
                        tbcelladdtc.Controls.Add(new LiteralControl("<br/>"));
                        DynRow1.Cells.Add(tbcelladdtc);
                    }

                    DynTable.Rows.Add(DynRow1);
                }
                
            }
            else
            {
                btnSave.Enabled = false;
                lblBatchName.Text = "";
            }
        }
        catch (Exception ex)
        {
            //sDRdr.Close();
            this.ClientScript.RegisterStartupScript(this.Page.GetType(), "Alert", "<script language=\"javascript\" type=\"text/javascript\" >alert(\"Error: " + ex.Message + "\");</script>", false);
        }

        hdnUpdateInd.Value = lsRowUpdateStatusStr.ToString();
        pnlTestCaseRow.Controls.Add(DynTable);
        pnlTestCaseRow.Visible = true;
        lblExistingBatch.Visible = false;
        lbDeleteSlctd.Visible = false;
        //*****************************************
        LinkButton lnkResetTC = new LinkButton();
        lnkResetTC.ID = "lnkRefreshTC";
        lnkResetTC.Click += new EventHandler(lnkResetTC_Click);
        pnlTcTransactionDetails.Controls.Add(lnkResetTC);
        //*****************************************
    }


    /// <summary>
    /// 
    /// </summary>
    /// <param name="clientid"></param>
    /// <param name="linkText"></param>
    void GenerateRowColumnID(string clientid, string linkText)
    {
        int MaxTrans = int.Parse(ConfigurationManager.AppSettings["MaxTrans"]);
        SqlDataReader sdr = null;
        lblTransactionDetails.Text = "";
        lsLinkClientId = "";
        lsLinkClientId = clientid.ToString();
        lsLinkClientId = lsLinkClientId.Remove(0, 3).ToString();
        liLnkPos = lsLinkClientId.IndexOf("_LNK_");

        lsColumnData = lsLinkClientId.Substring(0, liLnkPos).ToString();
        liRowId = lsLinkClientId.Substring(liLnkPos + 5, lsLinkClientId.Length - (liLnkPos + 5)).ToString();

        ViewState["lsColumnData"] = lsLinkClientId.Substring(0, liLnkPos).ToString();
        ViewState["liRowId"] = lsLinkClientId.Substring(liLnkPos + 5, lsLinkClientId.Length - (liLnkPos + 5)).ToString();


        //Check Transaction Count for a test case.....
        DataSet CheckItemsDta = new DataSet();
        try
        {
            CheckItemsDta = objSQL.ReturnDataAdapter("Select TransactionCnt,'[' + FirstTransaction + ']' + '[' + SecondTransaction + ']'+'[' + ThirdTransaction + ']'+'[' + FourthTransaction + ']'+'[' + FifthTransaction + ']' from TEST_CASE_SELECTION_SHEET_GEN_TB where FlowType='" + Session["FlowType"].ToString().Trim() + "' and userId='" + Session["UserId"].ToString() + "' and TestCase='TC" + liRowId.ToString() + "'");
            if (CheckItemsDta.Tables.Count > 0)
            {
                foreach (DataRow row in CheckItemsDta.Tables[0].Rows)
                {
                    countResult = int.Parse(row[0].ToString());
                    gsAllTransactions = row[1].ToString();
                }
            }
        }
        catch (Exception ex)
        {
            this.ClientScript.RegisterStartupScript(this.Page.GetType(), "Alert", "<script language=\"javascript\" type=\"text/javascript\" >alert(\"Error: " + ex.Message + "\");</script>", false);
            CheckItemsDta.Dispose();
        }
        finally
        {
            CheckItemsDta.Dispose();
        }

        //Check for number of transactions
        lblTransactionDetails.Text = (int)countResult < 5 ? "<font color=green size=2>    (Number of Trancation(s) added on TC" + liRowId.ToString() + " is " + countResult.ToString() + ".)</font>" : "<font color=red size=2>    <b>(You have already added 5 transactions to TC" + liRowId.ToString() + ". No more transactions are allowed.)</b></font>";
        ViewState["liTransactionCnt"] = (int)countResult;

        if ((int)ViewState["liTransactionCnt"] < MaxTrans)   //Checks if more transactions are allowed before validation
        {
            //Validate the current transaction
            if (gsAllTransactions.ToString().IndexOf("[" + ViewState["lsColumnData"].ToString().Replace("_", " ").Trim().ToString() + "]") != -1)
            {
                lblTransactionDetails.Text = lblTransactionDetails.Text + "<br/><br/><font color='#26282C'><b>User Error : Transactions have been added earlier under </font><font color=red>" + ViewState["lsColumnData"].ToString().Replace("_", " ").Trim().ToString() + ".</font><font color='#26282C'> Click Details to view it.</font></b><br/>";
                ViewState["liTransactionCnt"] = MaxTrans;  //Equated to 5 forcefully to make controls invisible
            }
            else
            {
                sdr = objSQL.ReturnDataReader("select distinct t2.FTEXT from [TC_FEILDS] t1 INNER JOIN [TC_FEILDS] t2 ON t1.F_DEPENDENT_ON = t2.FID where t1.FTEXT='" + ViewState["lsColumnData"].ToString().Replace("_", " ").Trim().ToString() + "'");

                if (sdr.HasRows)
                {
                    while (sdr.Read())
                    {
                        if (gsAllTransactions.ToString().IndexOf("["+sdr[0].ToString().Trim()+"]") == -1)
                        {
                            lblTransactionDetails.Text = lblTransactionDetails.Text + "<br/><br/><font color='#26282C'><b>User Error : Please add</font> <font color=red>'" + sdr[0].ToString().Trim() + "'</font><font color='#26282C'> before adding transactions under </font><font color=red>'" + ViewState["lsColumnData"].ToString().Replace("_", " ").Trim().ToString() + "'.</font></b><br/>";
                            ViewState["liTransactionCnt"] = MaxTrans;  //Equated to 5 forcefully to make controls invisible
                        }
                    }
                }
            }
        }
    }

    void lnkDeleteBatch_Click(object sender, EventArgs e)
    {
        StringBuilder sbSearchQry = new StringBuilder("");
        string lsBatchName = "";

        lsBatchName = ((LinkButton)sender).CommandName;
        hdnBatchName.Value = "";

        sbSearchQry.Append("Delete from Transaction_ARCH_TB where UsrId='" + Session["UserId"].ToString() + "' and DateTimeSaved='" + lsBatchName.ToString() + "' Delete from TEST_CASE_SELECTION_SHEET_GEN_ARCH_TB where UserId='" + Session["UserId"].ToString() + "' and FlowType='IB_HH' and DateTimeSaved='" + lsBatchName.ToString().Trim().ToString() + "' ");
        sbSearchQry.Append(" Delete from Transaction_TB where UsrId='" + Session["UserId"].ToString() + "' Delete from TEST_CASE_SELECTION_SHEET_GEN_TB where UserId='" + Session["UserId"].ToString() + "' and FlowType='IB_HH'  Delete from RESULTS_TB where UserId='" + Session["UserId"].ToString() + "' and FlowType='IB_HH' and BatchName='" + lsBatchName.ToString().Trim().ToString() + "'");

        try
        {
            int aff=objSQL.sqlExecuteNonQuery(sbSearchQry.ToString().Trim());
            CreateDynamicRows();
            LoadExistingBatches('y');
            pnlScenarios.Visible = false;
            if (aff > 0)
            {
                this.ClientScript.RegisterStartupScript(this.Page.GetType(), "Alert", "<script language=\"javascript\" type=\"text/javascript\" > alert(\"Batch deleted.\");</script>", false);
            }
        }
        catch (Exception ex)
        {
            this.ClientScript.RegisterStartupScript(this.Page.GetType(), "Alert", "<script language=\"javascript\" type=\"text/javascript\" > alert(\"Error: " + ex.Message + "\");</script>", false);
        }
        finally
        {
            lbDeleteSlctd.Visible = false;
        }
    }

    void lnkLoadBatch_Click(object sender, EventArgs e)
    {
        btnSave.Visible = false;
        btnUpdate.Visible = true;
        StringBuilder sbSearchQry = new StringBuilder("");
        string lsBatchName = ""; string lsBatchAliasName = "";

        lsBatchName = ((LinkButton)sender).CommandName;
        lsBatchAliasName = ((LinkButton)sender).OnClientClick;
        lsBatchAliasName = lsBatchAliasName.Remove(0, 47);
        lsBatchAliasName = lsBatchAliasName.Substring(0, lsBatchAliasName.IndexOf(")? Current"));
        hdnBatchName.Value = lsBatchName.ToString() + "~" + lsBatchAliasName;
        lblBatchName.Text = "<font color='#26282C'><b>Loaded Batch : </b></font> <b><font color=red>" + lsBatchAliasName.ToString() + "</font></b>";
       
        sbSearchQry.Append("Delete from Transaction_TB where UsrId='" + Session["UserId"].ToString() + "'and FlowType='" + Session["FlowType"].ToString().Trim() + "' Delete from TEST_CASE_SELECTION_SHEET_GEN_TB where UserId='" + Session["UserId"].ToString() + "' and FlowType='" + Session["FlowType"].ToString().Trim() + "'");
        sbSearchQry.Append(" Insert into Transaction_TB Select [TestCase],[Transaction],[UsrId],[SrlNmbr],[UpdateInd],[Flowtype],[Field] from Transaction_Arch_Tb where usrid='" + Session["UserId"].ToString() + "' and datetimesaved='" + lsBatchName.ToString().Trim().ToString() + "' and FlowType='" + Session["FlowType"].ToString().Trim() + "' Insert into TEST_CASE_SELECTION_SHEET_GEN_TB Select TestCase,FirstTransaction,SecondTransaction,ThirdTransaction,FourthTransaction,FifthTransaction,FlowType,UserId,TransactionCnt from TEST_CASE_SELECTION_SHEET_GEN_ARCH_TB where userid='" + Session["UserId"].ToString() + "' and Flowtype='" + Session["FlowType"].ToString().Trim() + "' and datetimesaved='" + lsBatchName.ToString().Trim().ToString() + "'");

        try
        {
            objSQL.sqlExecuteNonQuery(sbSearchQry.ToString().Trim());
            CreateDynamicRows();
            pnlScenarios.Visible = false;

            if (((LinkButton)sender).Text.Trim().ToString().IndexOf(">Y<") != -1)
            {
                btnSave.Enabled = false;
                lblBatchName.Text = "<font color='#26282C'><b>Loaded Batch : </b></font> <b><font color=red>" + lsBatchAliasName.ToString() + "</b> - Executed earlier.</font>";
            }
            else
            {
                btnSave.Enabled = true;
            }
        }
        catch (Exception ex)
        {
            this.ClientScript.RegisterStartupScript(this.Page.GetType(), "Alert", "<script language=\"javascript\" type=\"text/javascript\" > alert(\"Error: " + ex.Message + "\");</script>", false);
        }
        finally
        {
            lblEdittingFor.Text = "";
            lblExistingBatch.Visible = false;
            lbDeleteSlctd.Visible = false;
            btnRunBatch.Enabled = true;
            btnRunBatch.Visible = true;
        }
    }

    void lnkTC_Details_Click(object sender, EventArgs e)
    {
        CreateDynamicRows();
        string lsTransStr = "";
        lblEdittingFor.Text = "";
        lblTcTransactionDetails.Text = ((LinkButton)sender).ID;
        lblTcTransactionDetails.Text = "";
        
        DataSet CheckTCDta = new DataSet();
        try
        {
            CheckTCDta = objSQL.ReturnDataAdapter("Select * from Transaction_TB where TestCase='" + ((LinkButton)sender).ID.Trim().ToString() + "' and usrid='" + Session["UserId"].ToString() + "' and FlowType='" + Session["FlowType"].ToString().Trim() + "' and UpdateInd='Y'");
            if (CheckTCDta.Tables.Count > 0)
            {
                lblTcTransactionDetails.Text = lblTcTransactionDetails.Text + "<font color=red style='background : yellow'><b>Displaying transactions selected in " + ((LinkButton)sender).ID.Trim().ToString() + "</b></font><br/><br/>";
                foreach (DataRow row in CheckTCDta.Tables[0].Rows)
                {
                    //for (int i = 0; i < CheckTCDta.Tables[0].Rows.Count; i++)
                    //{
                            lblTcTransactionDetails.Text = lblTcTransactionDetails.Text + "&nbsp;&nbsp;<font color=brown><b>" + row["Field"].ToString() + "</b>:</font><br/>";
                            lsTransStr = "";
                            lsTransStr = row[1].ToString().Trim().ToString().Replace(",#", "").ToString();
                                                        
                            DataSet dsGroupnames = new DataSet();
                            try
                            {
                                dsGroupnames = objSQL.ReturnDataAdapter("Select distinct Group_Name from CollectionScenarios_TB_Generic where Index_Num in (" + lsTransStr.ToString() + ") and FlowType='" + Session["FlowType"].ToString().Trim() + "'");
                                if (dsGroupnames.Tables.Count > 0)
                                {
                                    foreach (DataRow Group in dsGroupnames.Tables[0].Rows)
                                    {
                                        try
                                        {
                                            DataSet dsActioNames = new DataSet();
                                            lblTcTransactionDetails.Text = lblTcTransactionDetails.Text + "<font color='#26282C'><div id='navcontainer'><ul><img src='Images/Dots.gif'></img>&nbsp;&nbsp;&nbsp;<b>" + Group[0].ToString() + "</b></font>" + "<br/>";
                                            dsActioNames = objSQL.ReturnDataAdapter("Select Action_Name from CollectionScenarios_TB_Generic where Index_Num in (" + lsTransStr.ToString() + ") and Group_Name='" + Group[0].ToString() + "' and FlowType='" + Session["FlowType"].ToString().Trim() + "'");
                                            if (dsActioNames.Tables.Count > 0)
                                            {
                                                foreach (DataRow ActioName in dsActioNames.Tables[0].Rows)
                                                {
                                                    lblTcTransactionDetails.Text = lblTcTransactionDetails.Text + "<font color='#26282C'><li><img src='Images/Gdot.gif'>&nbsp;&nbsp;&nbsp;" + ActioName[0].ToString() + "</li></font>" + "<br/>";
                                                }
                                            }
                                        }
                                        catch
                                        {
                                           
                                        }
                                        finally 
                                        {
                                            lblTcTransactionDetails.Text = lblTcTransactionDetails.Text + "</ul></div>";
                                        }
                                     }
                                }
                            }
                            catch (Exception ex)
                            {
                                this.ClientScript.RegisterStartupScript(this.Page.GetType(), "Alert", "<script language=\"javascript\" type=\"text/javascript\" > alert(\"Error: " + ex.Message + "\");</script>", false);
                                dsGroupnames.Dispose();
                            }
                            finally
                            {
                                dsGroupnames.Dispose();
                            }
                        //}

                    //}
                }
            }
        }
        catch (Exception ex)
        {
            this.ClientScript.RegisterStartupScript(this.Page.GetType(), "Alert", "<script language=\"javascript\" type=\"text/javascript\" > alert(\"Error: " + ex.Message + "\");</script>", false);
        }
        finally
        {
            if (lblTcTransactionDetails.Text.IndexOf("<li>") == -1)
            {
                lblTcTransactionDetails.Text = lblTcTransactionDetails.Text + "<font color='#26282C'>* No transactions added so far for " + ((LinkButton)sender).ID.Trim().ToString() + "</font>";
            }
            else
            {
                LinkButton lnkResetTC = new LinkButton();
                lnkResetTC.ID = "lnkRefreshTC";
                lnkResetTC.Text = "<br/><font color=white style='background : red'>&nbsp;Delete all Transactions under " + ((LinkButton)sender).ID.Trim().ToString() + "?&nbsp;</font>";
                lnkResetTC.Click += new EventHandler(lnkResetTC_Click);
                lnkResetTC.OnClientClick = "if (!confirm('Are you sure to delete all Transactions added under " + ((LinkButton)sender).ID.Trim().ToString() + "?')) return false";
                ViewState["TestCase"] = ((LinkButton)sender).ID.Trim().ToString();
                pnlTcTransactionDetails.Controls.Add(lnkResetTC);
            }
            CheckTCDta.Dispose();
        }

        pnlTcTransactionDetails.Visible = true;
        lblExistingBatch.Visible = false;
        lbDeleteSlctd.Visible = false;
    }

    void lnkResetTC_Click(object sender, EventArgs e)
    {
        string sbSearchQry = string.Empty;
        sbSearchQry = "Update Transaction_TB set Transactiontext='-',UpdateInd='N' where TestCase='" + ViewState["TestCase"].ToString() + "' and UsrId='" + Session["UserId"].ToString() + "' and FlowType='" + Session["FlowType"].ToString().Trim() + "'";
        sbSearchQry = sbSearchQry + " Update TEST_CASE_SELECTION_SHEET_GEN_TB set FirstTransaction='',SecondTransaction='',ThirdTransaction='',FourthTransaction='',FifthTransaction='',TransactionCnt=0 where TestCase='" + ViewState["TestCase"].ToString() + "' and FlowType='" + Session["FlowType"].ToString().Trim() + "' and userid='" + Session["UserId"].ToString() + "'";

        try
        {
            objSQL.sqlExecuteNonQuery(sbSearchQry.ToString().Trim());
            CreateDynamicRows();
            pnlScenarios.Visible = false;
            lblEdittingFor.Text = "";
            hdnTest.Value = "";
            pnlTcTransactionDetails.Visible = false;
            lblTransactionDetails.Text = "<font color='green'><b>Test Case " + ViewState["TestCase"].ToString() + " has been reset. You can now add new transactions to this test case.</b></font><br/>";
            ViewState["TestCase"] = "";
        }
        catch (Exception ex)
        {
            this.ClientScript.RegisterStartupScript(this.Page.GetType(), "Alert", "<script language=\"javascript\" type=\"text/javascript\" > alert(\"Error: " + ex.Message + "\");</script>", false);
        }
        finally
        {
            btnSave.Enabled = false;
        }
    }

    void lnkDelete_Click(object sender, EventArgs e)
    {
        lblTransactionDetails.Text = "";
        isReady4InsertData = false;
        pnlTestCaseRow.Visible = false;
        pnlTcTransactionDetails.Visible = false;
        GenerateRowColumnID(((ImageButton)sender).ID, "Delete");
        ContentPlaceHolder mainContent = (ContentPlaceHolder)this.Master.FindControl("ContentPlaceHolder1");
        Table tbTC = ((System.Web.UI.WebControls.Table)mainContent.FindControl("TbTestCaseTransactions"));
        StringBuilder sbSearchQry = new StringBuilder("");
        sbSearchQry.Append("Delete from Transaction_Tb where UsrId='" + Session["UserId"].ToString() + "' and TestCase='TC" + liRowId.ToString().Trim().ToString() + "' and FlowType='" + Session["FlowType"].ToString().Trim() + "' Delete from TEST_CASE_SELECTION_SHEET_GEN_TB where UserId='" + Session["UserId"].ToString() + "' and FlowType='" + Session["FlowType"].ToString().Trim() + "'  and TestCase='TC" + liRowId.ToString().Trim().ToString() + "'");

        try
        {
            objSQL.sqlExecuteNonQuery(sbSearchQry.ToString().Trim());
        }
        catch (Exception ex)
        {
            this.ClientScript.RegisterStartupScript(this.Page.GetType(), "Alert", "<script language=\"javascript\" type=\"text/javascript\" > alert(\"Error: " + ex.Message + "\");</script>", false);
        }
        finally
        {
            //((System.Web.UI.WebControls.Table)mainContent.FindControl("TbTestCaseTransactions")).Controls.Clear();
            CreateDynamicRows();
            lblTransactionDetails.Text = "<b>Test Case " + liRowId + " has been deleted.</b><br/>";
            if (tbTC.Rows.Count > 1)
            {
                //lnkbtnAddCase.Visible = true;
            }
            else
            {
                //lnkbtnAddCase.Visible = false;
            }
        }
    }

    void lnkbtn_Click(object sender, EventArgs e)
    {
        GenerateRowColumnID(((LinkButton)sender).ID, ((LinkButton)sender).Text);
        lblEdittingFor.Text = "<font color='#26282C'>Editting for : </font>" + lsColumnData.Replace("_", " ") + " - (Test Case " + liRowId + ")";
        CreateDynamicRows();
        string txtclicked = ((LinkButton)sender).Text.Substring(((LinkButton)sender).Text.IndexOf('>')+1);
        txtclicked = txtclicked.Substring(0,txtclicked.IndexOf('<'));
        DisplayCheckBoxes(txtclicked);
    }

    //Add rows
    protected void doAddRow(object sender, EventArgs e)
    {
        if (txtTestCases.Text.Trim().ToString() == "0" || txtTestCases.Text.Trim().ToString() == "")
        {
            this.ClientScript.RegisterStartupScript(this.Page.GetType(), "Alert", "<script language=\"javascript\" type=\"text/javascript\" > alert(\"Error: Number of test cases should be greater than 0.\");</script>", false);
        }
        else
        {
            try
            {
                ViewState["TC"] = txtTestCases.Text.Trim();
                isReady4InsertData = true;
                CreateDynamicRows();
                lblTransactionDetails.Text = "";
                hdnTest.Value = "";
                pnlScenarios.Visible = false;
                lblEdittingFor.Text = "";
                isReady4InsertData = false;
                pnlTcTransactionDetails.Visible = false;
                hdnBatchName.Value = "";
                lblBatchName.Text = "";
                btnRunBatch.Visible = true;
                btnRunBatch.Enabled = false;
                btnSave.Visible = true;
                btnUpdate.Visible = false;
                //lnkbtnAddCase.Visible = true;
            }
            catch(Exception ex) 
            { 
            
            }
        }
    }

    protected void btnRefresh_Click(object sender, EventArgs e)
    {
        CreateDynamicRows();
        pnlScenarios.Visible = false;
        lblEdittingFor.Text = "";
        hdnTest.Value = "";
        lblExistingBatch.Visible = false;
        lbDeleteSlctd.Visible = false;
        lblTransactionDetails.Text = "";
        pnlTcTransactionDetails.Visible = false;
    }

    protected void btnReset_Click(object sender, EventArgs e)
    {
        btnRunBatch.Visible = false;
        pnlScenarios.Visible = false;
        lblEdittingFor.Text = "";
        hdnTest.Value = "";
        txtTestCases.Text = "1";
        lblTransactionDetails.Text = "";
        isReady4InsertData = false;
        pnlTcTransactionDetails.Visible = false;
        hdnBatchName.Value = "";
        btnSave.Visible = false;
        btnUpdate.Visible = false;
        //lnkbtnAddCase.Visible = false;
        StringBuilder sbSearchQry = new StringBuilder("");
        sbSearchQry.Append("Delete from Transaction_TB where UsrId='" + Session["UserId"].ToString() + "' and FlowType='" + Session["FlowType"].ToString().Trim() + "' Delete from TEST_CASE_SELECTION_SHEET_GEN_TB where UserId='" + Session["UserId"].ToString() + "' and FlowType='" + Session["FlowType"].ToString().Trim() + "' ");
        try
        {
            objSQL.sqlExecuteNonQuery(sbSearchQry.ToString().Trim());
        }
        catch (Exception ex)
        {
            this.ClientScript.RegisterStartupScript(this.Page.GetType(), "Alert", "<script language=\"javascript\" type=\"text/javascript\" > alert(\"Error: " + ex.Message + "\");</script>", false);
        }
        finally
        {
            hdnBatchName.Value = "";
            lblExistingBatch.Visible = false;
            lbDeleteSlctd.Visible = false;
            lblBatchName.Text = "";
            btnSave.Enabled = false;
        }
    }


    protected void btnExistingBatch_Click(object sender, EventArgs e)
    {
        pnlExistingBatch.Controls.Clear();
        CreateDynamicRows();
        lblEdittingFor.Text = "";
        hdnDelID.Value = "";
        LoadExistingBatches('y');
        try
        {
            int rowcnt = int.Parse(objSQL.sqlExecuteScalar("Select distinct count(DateTimeSaved) as Cnt from Transaction_Arch_Tb where usrid='" + Session["UserId"].ToString() + "' and FlowType='" + Session["FlowType"].ToString().Trim() + "'"));
            if (rowcnt < 1)
            {
                this.ClientScript.RegisterStartupScript(this.Page.GetType(), "Alert", "<script language=\"javascript\" type=\"text/javascript\" >alert(\"No saved batches found for '" + lblFlowType.Text + "'\");</script>", false);
            }
        }
        catch (Exception ex)
        {
            this.ClientScript.RegisterStartupScript(this.Page.GetType(), "Alert", "<script language=\"javascript\" type=\"text/javascript\" >alert(\"Error: " + ex.Message + "\");</script>", false);
        }
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        CreateDynamicRows();
        pnlScenarios.Visible = false;
        lblEdittingFor.Text = "";
        hdnTest.Value = "";
        lblTransactionDetails.Text = "";
        pnlTcTransactionDetails.Visible = false;
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        string sbSearchQry = string.Empty;
        string lsUpdateInd = "";
        lsTransactonName = "";
        lblTransactionDetails.Text = "";
        pnlTcTransactionDetails.Visible = false;

        SqlConnection sConn = new SqlConnection(ConfigurationManager.ConnectionStrings["PortalConnectionString"].ConnectionString);
        sConn.Open();

        if (hdnTest.Value.ToString() == "")
        {
            lblEdittingFor.Text = "Error: No Transactions added for this test case. Nothing updated. Please try again. <br/>";
            CreateDynamicRows();
            pnlScenarios.Visible = false;
            hdnTest.Value = "";
            hdnTest.Value = "-";
            lsUpdateInd = "N";
        }
        else
        {
            string strindexes = "";
            hdnTest.Value = hdnTest.Value.ToString().Replace("[", "'").Replace("]", "'").ToString() + "#";
            hdnTest.Value = hdnTest.Value.ToString().Replace(",#", "");
            foreach (string s in hdnTest.Value.Split(new char[] { ',' }))
            {
                if (s != "")
                {
                    SqlCommand cmd = new SqlCommand("");
                    DataSet CheckItemsIndex = new DataSet();
                    try
                    {
                        cmd = new SqlCommand("Select Index_Num,Action_Name from CollectionScenarios_TB_Generic where Group_Name =" + s.Trim().ToString() + " and FlowType='" + Session["FlowType"].ToString().Trim() + "'", sConn);//hk
                        SqlDataAdapter sda = new SqlDataAdapter(cmd);
                        sda.Fill(CheckItemsIndex);
                        if (CheckItemsIndex.Tables.Count > 0)
                        {
                            foreach (DataRow row in CheckItemsIndex.Tables[0].Rows)
                            {
                                if (strindexes == "")
                                { strindexes = "[" + row["Index_Num"].ToString().Trim() + "]"; }
                                else
                                { strindexes += ",[" + row["Index_Num"].ToString().Trim() + "]"; }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        sConn.Close();
                        cmd.Dispose();
                        CheckItemsIndex.Dispose();
                        sConn.Dispose();
                        this.ClientScript.RegisterStartupScript(this.Page.GetType(), "Alert", "<script language=\"javascript\" type=\"text/javascript\" >alert(\"Error: " + ex.Message + "\");</script>", false);
                    }
                }
            }
            if (int.Parse(hdnChangeStatus.Value.Trim()) == 1)
            {
                if (Session["UnchkID"].ToString().Trim() != "")
                {
                    string ignoreID = Session["UnchkID"].ToString().Trim().ToString();
                    string[] strArray;
                    strArray = ignoreID.Split(new char[] { ',' });
                    for (int item = 0; item < strArray.Length - 1; item++)
                    {
                        strindexes = strindexes.Replace(strArray[item].Trim() + ",", "").Replace(strArray[item].Trim(), "");
                    }
                }
            }
            lsUpdateInd = "Y";
            hdnTest.Value = strindexes.Replace("[", "").Replace("]", "") + ",#";


            switch ((int)ViewState["liTransactionCnt"])
            {
                case 0:
                    lsTransactonName = "FirstTransaction";
                    break;
                case 1:
                    lsTransactonName = "SecondTransaction";
                    break;
                case 2:
                    lsTransactonName = "ThirdTransaction";
                    break;
                case 3:
                    lsTransactonName = "FourthTransaction";
                    break;
                case 4:
                    lsTransactonName = "FifthTransaction";
                    break;
                case 5:
                    lsTransactonName = "*Not Allowed*";  // Not being used anywhere as we are not allowing it.
                    break;
            }

            sbSearchQry = "Update Transaction_TB set TransactionText='" + hdnTest.Value.ToString() + "',UpdateInd='" + lsUpdateInd.ToString() + "' where Field='" + ViewState["lsColumnData"].ToString().Replace("_", " ").Trim() + "' and TestCase='TC" + ViewState["liRowId"].ToString() + "' and UsrId='" + Session["UserId"].ToString() + "' and FlowType='" + Session["FlowType"].ToString().Trim() + "'";
            sbSearchQry = sbSearchQry + " Update TEST_CASE_SELECTION_SHEET_GEN_TB set " + lsTransactonName.ToString().Trim().ToString() + "='" + ViewState["lsColumnData"].ToString().Replace("_", " ").Trim() + "', TransactionCnt=TransactionCnt+1 where TestCase='TC" + ViewState["liRowId"].ToString() + "' and FlowType='" + Session["FlowType"].ToString().Trim() + "' and userid='" + Session["UserId"].ToString() + "'";

            SqlCommand cmdUpdateData = new SqlCommand(sbSearchQry.ToString(), sConn);
            try
            {
                cmdUpdateData.ExecuteNonQuery();
                CreateDynamicRows();
                pnlScenarios.Visible = false;
                lblEdittingFor.Text = "";
                hdnTest.Value = "";
            }
            catch (Exception ex)
            {
                this.ClientScript.RegisterStartupScript(this.Page.GetType(), "Alert", "<script language=\"javascript\" type=\"text/javascript\" > alert(\"Error: " + ex.Message + "\");</script>", false);
                sConn.Close();
                cmdUpdateData.Dispose();
                sConn.Dispose();
            }
            finally
            {
                sConn.Close();
                cmdUpdateData.Dispose();
                sConn.Dispose();
            }
        }
    }

    protected void lbDeleteSlctd_Click(object sender, EventArgs e)
    {
        StringBuilder sbDelQry = new StringBuilder("");
        hdnDelID.Value = hdnDelID.Value.ToString().Replace("[", "").Replace("]", "").Replace("ctl05,", "").ToString();
        ArrayList ArrDelID = new ArrayList();
        ArrDelID.AddRange(hdnDelID.Value.Split(','));
        ArrDelID.Remove("");

        try
        {
            pnlScenarios.Visible = false;
            foreach (string id in ArrDelID)
            {
                sbDelQry.Append("Delete from Transaction_Arch_Tb where UsrId='" + Session["UserId"].ToString() + "' and DateTimeSaved='" + id.ToString().Trim() + "'and FlowType='" + Session["FlowType"].ToString().Trim() + "' Delete from TEST_CASE_SELECTION_SHEET_GEN_ARCH_TB where UserId='" + Session["UserId"].ToString() + "' and FlowType='" + Session["FlowType"].ToString().Trim() + "' and DateTimeSaved='" + id.ToString().Trim().ToString() + "' ");
                sbDelQry.Append(" Delete from Transaction_TB where UsrId='" + Session["UserId"].ToString() + "' and FlowType='" + Session["FlowType"].ToString().Trim() + "' Delete from TEST_CASE_SELECTION_SHEET_GEN_TB where UserId='" + Session["UserId"].ToString() + "' and FlowType='" + Session["FlowType"].ToString().Trim() + "'  Delete from RESULTS_TB where UserId='" + Session["UserId"].ToString() + "' and FlowType='" + Session["FlowType"].ToString().Trim() + "' and BatchName='" + id.ToString().Trim().ToString() + "'");
                objSQL.sqlExecuteNonQuery(sbDelQry.ToString().Trim());
            }
            ContentPlaceHolder mainContent = (ContentPlaceHolder)this.Master.FindControl("ContentPlaceHolder1");
            //((System.Web.UI.WebControls.Table)mainContent.FindControl("TbTestCaseTransactions")).Controls.Clear();
            CreateDynamicRows();
        }
        catch (Exception ex)
        {
            this.ClientScript.RegisterStartupScript(this.Page.GetType(), "Alert", "<script language=\"javascript\" type=\"text/javascript\" > alert(\"Error: " + ex.Message + "\");</script>", false);
        }
        finally
        {
            lblExistingBatch.Visible = false;
            lbDeleteSlctd.Visible = false;
            hdnDelID.Value = "";
            LoadExistingBatches('y');
            this.ClientScript.RegisterStartupScript(this.Page.GetType(), "Alert", "<script language=\"javascript\" type=\"text/javascript\" > alert(\"Batch(es) deleted.\");</script>", false);
        }
    }

    public bool BatchAlreadyExists(string Batchname)
    {
        SqlDataReader SDR;
        bool exists = false;
        try
        {
            SDR = objSQL.ReturnDataReader("select * from TRANS_ARCH_TB where AliasBatchName='" + Batchname + "'"); ;
            if (SDR.HasRows) { exists = true; }
        }
        catch (Exception ex)
        {
            this.ClientScript.RegisterStartupScript(this.Page.GetType(), "Alert", "<script language=\"javascript\" type=\"text/javascript\" > alert(\"Error: " + ex.Message + "\");</script>", false);
        }
        return exists;
    }

    protected void btnSave_Click(int btnStats)
    {
        string lsBatchName = "";
        StringBuilder sbSearchQry = new StringBuilder("");

        lsBatchName = DateTime.Now.ToString("ddMMyyyyhhmmss");
        if (btnStats == 1)
        {
            sbSearchQry.Append("Insert into Transaction_Arch_Tb SELECT [TestCase],[TransactionText],[UsrId],[SrlNmbr],[UpdateInd],'" + lsBatchName.ToString().Trim().ToString() + "','','',0,'" + txtBtchName.Text.ToString().Trim() + "',FlowType,Field from Transaction_TB where usrid='" + Session["UserId"].ToString() + "'and FlowType='" + Session["FlowType"].ToString().Trim() + "' Insert into TEST_CASE_SELECTION_SHEET_GEN_ARCH_TB Select TestCase,FirstTransaction,SecondTransaction,ThirdTransaction,FourthTransaction,FifthTransaction,FlowType,UserId,TransactionCnt,'" + lsBatchName.ToString().Trim().ToString() + "','" + txtBtchName.Text.Trim() + "' from TEST_CASE_SELECTION_SHEET_GEN_TB where userid='" + Session["UserId"].ToString() + "' and flowtype='" + Session["FlowType"].ToString().Trim() + "' ");
        }
        else if (btnStats == 0)
        {
            //sbSearchQry.Append("Insert into Transaction_Arch_Tb Select TestCase," + TRANS_ARCH_TB_COLS + ",UsrId,SrlNmbr,UpdateInd,'" + lsBatchName.Trim().ToString() + "','','',0,'" + lsBatchName.Trim().ToString() + "',FlowType from Transaction_TB where usrid='" + Session["UserId"].ToString() + "' and FlowType='" + Session["FlowType"].ToString().Trim() + "' Insert into TEST_CASE_SELECTION_SHEET_GEN_ARCH_TB Select TestCase,FirstTransaction,SecondTransaction,ThirdTransaction,FourthTransaction,FifthTransaction,FlowType,UserId,TransactionCnt,'" + lsBatchName.ToString().Trim() + "','" + lsBatchName.ToString().Trim() + "' from TEST_CASE_SELECTION_SHEET_GEN_TB where userid='" + Session["UserId"].ToString() + "' and flowtype='" + Session["FlowType"].ToString().Trim() + "'");
        }
        try
        {
            objSQL.sqlExecuteNonQuery(sbSearchQry.ToString().Trim());
            ContentPlaceHolder mainContent = (ContentPlaceHolder)this.Master.FindControl("ContentPlaceHolder1");
            //((System.Web.UI.WebControls.Table)mainContent.FindControl("TbTestCaseTransactions")).Controls.Clear();
            CreateDynamicRows();
            pnlScenarios.Visible = false;
            btnUpdate.Visible = true;
            btnSave.Visible = false;
        }
        catch (Exception ex)
        {
            this.ClientScript.RegisterStartupScript(this.Page.GetType(), "Alert", "<script language=\"javascript\" type=\"text/javascript\" > alert(\"Error: " + ex.Message + "\");</script>", false);
        }
        finally
        {
            btnRunBatch.Enabled = true;
            if (txtBtchName.Text != "")
            {
                lblBatchName.Text = "<font color='#26282C'><b>Loaded Batch : </b></font><b><font color=red>" + txtBtchName.Text.ToString().Trim() + "</font></b>";
                hdnBatchName.Value = lsBatchName.ToString() + "|" + txtBtchName.Text.ToString().Trim();
            }
            else
            {
                lblBatchName.Text = "<font color='#26282C'><b>Loaded Batch : </b></font><b><font color=red>" + lsBatchName.ToString().Trim() + "</font></b>";
                hdnBatchName.Value = lsBatchName.ToString().Trim() + "|" + lsBatchName.ToString().Trim();
            }
            txtBtchName.Text = "";
            this.ClientScript.RegisterStartupScript(this.Page.GetType(), "Alert", "<script language=\"javascript\" type=\"text/javascript\" > alert(\"Batch Saved.\");</script>", false);
        }
    }

    protected void btnchngName_Click(object sender, EventArgs e)
    {
        //if (hdnBtnName.Value.Trim() == "Save")
        //{
            bool exists = BatchAlreadyExists(txtBtchName.Text.Trim());
            if (exists == false)
            {
                btnSave_Click(1);
            }
            else
            {
                ContentPlaceHolder mainContent = (ContentPlaceHolder)this.Master.FindControl("ContentPlaceHolder1");
                //((System.Web.UI.WebControls.Table)mainContent.FindControl("TbTestCaseTransactions")).Controls.Clear();
                CreateDynamicRows();
                pnlScenarios.Visible = false;
                this.ClientScript.RegisterStartupScript(this.Page.GetType(), "Alert", "<script language=\"javascript\" type=\"text/javascript\" > alert(\"Batch with same name already exists.Batch not Saved.\");</script>", false);
            }
        //}
    }


    protected void btnDefualtSave_Click(object sender, EventArgs e)
    {
        hdnBatchName.Value = "";
        btnSave_Click(0);
    }

    protected void btnUpdateFinal_Click(object sender, EventArgs e)
    {
       
        string lsBatchName = "";
        string lsbatchAliasName = "";
        StringBuilder sbSearchQry = new StringBuilder("");
        lsBatchName = hdnBatchName.Value.Substring(0, 14);
        if (rbtnOld.Checked == true)
        {
            try
            {
                lsbatchAliasName = objSQL.sqlExecuteScalar("SELECT AliasBatchName FROM [AvivaTPortal].[dbo].[Transaction_Arch_Tb] where DateTimeSaved='" + lsBatchName.Trim() + "' and UsrId='" + Session["UserId"].ToString().Trim() + "'").ToString().Trim();
                if (lsbatchAliasName == "")
                {
                    lsbatchAliasName = lsBatchName;
                }
                sbSearchQry.Append("Delete from Transaction_Arch_Tb where UsrId='" + Session["UserId"].ToString() + "' and DateTimeSaved='" + lsBatchName.ToString().Trim().ToString() + "' Delete from TEST_CASE_SELECTION_SHEET_GEN_ARCH_TB where UserId='" + Session["UserId"].ToString() + "' and FlowType='" + Session["FlowType"].ToString().Trim() + "' and DateTimeSaved='" + lsBatchName.ToString().Trim().ToString() + "' ");
                sbSearchQry.Append("Insert into Transaction_Arch_Tb Select [TestCase],[Transactiontext],[UsrId],[SrlNmbr],[UpdateInd],'" + lsBatchName.Trim().ToString() + "','','',0,'" + lsbatchAliasName.Trim().ToString() + "',FlowType,Field from Transaction_TB where usrid='" + Session["UserId"].ToString() + "' and FlowType='" + Session["FlowType"].ToString().Trim() + "' Insert into TEST_CASE_SELECTION_SHEET_GEN_ARCH_TB Select TestCase,FirstTransaction,SecondTransaction,ThirdTransaction,FourthTransaction,FifthTransaction,FlowType,UserId,TransactionCnt,'" + lsBatchName.ToString().Trim() + "','" + lsbatchAliasName.ToString().Trim() + "' from TEST_CASE_SELECTION_SHEET_GEN_TB where userid='" + Session["UserId"].ToString() + "' and flowtype='" + Session["FlowType"].ToString().Trim() + "' ");
                objSQL.sqlExecuteNonQuery(sbSearchQry.ToString().Trim());
                CreateDynamicRows();
                pnlScenarios.Visible = false;
            }
            catch (Exception ex)
            {
                this.ClientScript.RegisterStartupScript(this.Page.GetType(), "Alert", "<script language=\"javascript\" type=\"text/javascript\" > alert(\"Error: " + ex.Message + "\");</script>", false);
            }
            finally
            {
                btnRunBatch.Enabled = true;
                hdnBatchName.Value = lsBatchName.ToString() + "~" + lsbatchAliasName.ToString().Trim();
                txtBtchName.Text = "";
                this.ClientScript.RegisterStartupScript(this.Page.GetType(), "Alert", "<script language=\"javascript\" type=\"text/javascript\" > alert(\"Batch Updated.\");</script>", false);
            }
        }
        else if (rbtnNew.Checked == true)
        {
            bool exists = BatchAlreadyExists(txtBtchName.Text.Trim());
            if (exists == false)
            {
                btnSave_Click(1);
            }
            else
            {
                CreateDynamicRows();
                pnlScenarios.Visible = false;
                this.ClientScript.RegisterStartupScript(this.Page.GetType(), "Alert", "<script language=\"javascript\" type=\"text/javascript\" > alert(\"Batch with same name already exists.Batch not Saved.\");</script>", false);
            }
        }
    }

    protected void lnkbtnAddCase_Click(object sender, EventArgs e)
    {
        if (txtTestCases.Text.Trim().ToString() == "0" || txtTestCases.Text.Trim().ToString() == "")
        {
            this.ClientScript.RegisterStartupScript(this.Page.GetType(), "Alert", "<script language=\"javascript\" type=\"text/javascript\" > alert(\"Error: Number of test cases should be greater than 0.\");</script>", false);
        }
        else
        {
            DataSet dsFeilds = objSQL.ReturnDataAdapter("select FID,FTEXT from [TC_FEILDS] INNER JOIN [Menu] ON [TC_FEILDS].BUS_TYPE=[Menu].BUS_TYPE WHERE [Menu].[MenuID]='" + Session["FlowType"] + "' ");
            DataSet ds = new DataSet();
            ds = objSQL.ReturnDataAdapter("Select MAX(SrlNmbr) from Transaction_Tb where UsrId='" + Session["UserId"].ToString() + "'and FlowType='" + Session["FlowType"].ToString().Trim() + "'");
            int largstTCVal = int.Parse(ds.Tables[0].Rows[0][0].ToString()) + 1;

            try
            {
                StringBuilder sbAddNewTC = new StringBuilder("");
                foreach (DataRow row in dsFeilds.Tables[0].Rows)
                {
                    sbAddNewTC.Append("Insert into Transaction_Tb([TestCase],[TransactionText],[UsrId],[SrlNmbr],[UpdateInd],[FlowType],[Field]) values('TC" + largstTCVal + "','-','" + Session["UserId"].ToString() + "'," + largstTCVal.ToString() + ",'N','" + Session["FlowType"].ToString().Trim() + "','" + row[1].ToString().Trim() + "') Insert into TEST_CASE_SELECTION_SHEET_GEN_TB values('TC" + largstTCVal + "','','','','','','" + Session["FlowType"].ToString().Trim() + "','" + Session["UserId"].ToString() + "',0)");
                    //ContentPlaceHolder mainContent = (ContentPlaceHolder)this.Master.FindControl("ContentPlaceHolder1");
                    //((System.Web.UI.WebControls.Table)mainContent.FindControl("TbTestCaseTransactions")).Dispose();
                }
                objSQL.sqlExecuteNonQuery(sbAddNewTC.ToString());
            }
            catch (Exception ex)
            {
                this.ClientScript.RegisterStartupScript(this.Page.GetType(), "Alert", "<script language=\"javascript\" type=\"text/javascript\" > alert(\"Error: " + ex.Message + "\");</script>", false);
            }
            finally
            {
                isReady4InsertData = true;
                pnlTestCaseRow.Controls.Clear();
                createdynamicfinally();
                lblTransactionDetails.Text = "";
                hdnTest.Value = "";
                pnlScenarios.Visible = false;
                lblEdittingFor.Text = "";
                isReady4InsertData = false;
                pnlTcTransactionDetails.Visible = false;
                lblBatchName.Text = "";
            }
        }
    }

    protected void btnRunBatch_Click(object sender, EventArgs e)
    {
        StringBuilder sbSearchQry = new StringBuilder("");
        string lsBatchName = "";
        string lsAliasBatchName = "";
        //string ipName = System.Net.Dns.GetHostEntry(Request.ServerVariables["remote_addr"]).HostName;
        string ipaddr = Request.UserHostAddress;
        lsBatchName = hdnBatchName.Value.ToString().Substring(0, 14).Trim();
        lsAliasBatchName = hdnBatchName.Value.ToString().Substring(15).Trim();

        sbSearchQry.Append("Delete from Transaction_Arch_Tb where UsrId='" + Session["UserId"].ToString() + "' and DateTimeSaved='" + lsBatchName.ToString().Trim().ToString() + "' and FlowType='" + Session["FlowType"].ToString().Trim() + "' Delete from TEST_CASE_SELECTION_SHEET_GEN_ARCH_TB where UserId='" + Session["UserId"].ToString() + "' and FlowType='" + Session["FlowType"].ToString().Trim() + "' and DateTimeSaved='" + lsBatchName.ToString().Trim().ToString() + "' ");
        sbSearchQry.Append("Insert into Transaction_Arch_Tb Select [TestCase],[Transactiontext],[UsrId],[SrlNmbr],[UpdateInd],'" + lsBatchName.ToString().Trim().ToString() + "','Y','" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "',0,'" + lsAliasBatchName.Trim() + "',FlowType,Field from Transaction_TB where usrid='" + Session["UserId"].ToString() + "' and FlowType='" + Session["FlowType"].ToString().Trim() + "' Insert into TEST_CASE_SELECTION_SHEET_GEN_ARCH_TB Select TestCase,FirstTransaction,SecondTransaction,ThirdTransaction,FourthTransaction,FifthTransaction,FlowType,UserId,TransactionCnt,'" + lsBatchName.ToString().Trim().ToString() + "','" + lsAliasBatchName.Trim() + "' from TEST_CASE_SELECTION_SHEET_GEN_TB where userid='" + Session["UserId"].ToString() + "' and flowtype='" + Session["FlowType"].ToString().Trim() + "'");
        sbSearchQry.Append("Delete from QTP_INPUT where SYSID='" + ipaddr + "'");
        sbSearchQry.Append("Insert into QTP_INPUT(SYSID,BatchID,EMail,[User],QCUser,QCPass) values('" + ipaddr + "','" + lsBatchName.ToString() + "','" + "-" + "','" + Session["UserId"].ToString() + "','-','-')");
        try
        {
            objSQL.sqlExecuteNonQuery(sbSearchQry.ToString().Trim());
            pnlScenarios.Visible = false;
        }
        catch (Exception ex)
        {
            this.ClientScript.RegisterStartupScript(this.Page.GetType(), "Alert", "<script language=\"javascript\" type=\"text/javascript\" > alert(\"Error: " + ex.Message + "\");</script>", false);
        }
        finally
        {
            this.ClientScript.RegisterStartupScript(this.Page.GetType(), "Alert", "<script language=\"javascript\" type=\"text/javascript\" > OpenQTPWin('" + Session["UserId"].ToString() + "|" + hdnBatchName.Value.ToString() + "','" + Session["FlowType"].ToString() + "');</script>", false);
            CreateDynamicRows();
            lblEdittingFor.Text = "";
        }
    }
}